package cn.tedu.web;

import cn.tedu.dao.UserDAO;
import cn.tedu.dao.UserDAOImpl;
import cn.tedu.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("*.do")
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String url = req.getRequestURI();
        url = url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
        System.out.println("---------"+url);
        UserDAO dao = new UserDAOImpl();
        if("/findAll".equals(url)){
            List<User> userList = dao.findAll();
            req.setAttribute("userList",userList);
            req.getRequestDispatcher("findAll.jsp").forward(req,resp);
        }else if("/addUser".equals(url)){

            PrintWriter out = resp.getWriter();
            String name = req.getParameter("name");
            System.out.println("-------"+name);
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            //入库操作
            User user = new User(name,username,password);
            int row = dao.insert(user);
            if(row!=1){
                resp.sendRedirect("reg.html");
            }else{
                resp.sendRedirect("findAll.do");
            }
        }else if("/delete".equals(url)){
            int id  = Integer.parseInt(req.getParameter("id"));
            int row = dao.delete(id);
            resp.sendRedirect("findAll.do");

        }
    }
}

















